package controller

import (
	"bytes"
	"fmt"
	"fx_swift_ifcgate_agent/api"
	"fx_swift_ifcgate_agent/internal/service"
	"fx_swift_ifcgate_agent/pkg/code"
	"fx_swift_ifcgate_agent/pkg/global"
	"fx_swift_ifcgate_agent/pkg/internalerrors"
	"fx_swift_ifcgate_agent/pkg/upload"
	"github.com/gin-gonic/gin"
	"github.com/xuri/excelize/v2"
	"net/http"
)

// 收款记录
func TradeReceiptList(c *gin.Context) {
	req := &api.TradeReceiptListReq{}
	if err := c.ShouldBindJSON(&req); err != nil {
		code.Fail(c, http.StatusBadRequest, code.ErrEncodingJSON, err.Error())
		return
	}
	result, err := service.NewTransferSrv().TradeReceiptList(c, req)
	if err != nil {
		code.Fail(c, http.StatusBadRequest, err.(internalerrors.ServiceError).Code, err.(internalerrors.ServiceError).Msg)
		return
	} else {
		code.Success(c, result)
	}
}

// 国际汇款记录
func InternationTransferList(c *gin.Context) {
	req := &api.ITListReq{}
	if err := c.ShouldBindJSON(&req); err != nil {
		code.Fail(c, http.StatusBadRequest, code.ErrEncodingJSON, err.Error())
		return
	}
	result, err := service.NewTransferSrv().InternationTransferList(c, req)
	if err != nil {
		code.Fail(c, http.StatusBadRequest, err.(internalerrors.ServiceError).Code, err.(internalerrors.ServiceError).Msg)
		return
	} else {
		code.Success(c, result)
	}
}

// 国内汇款记录
func DomesticTransferList(c *gin.Context) {
	req := &api.DTListReq{}
	if err := c.ShouldBindJSON(&req); err != nil {
		code.Fail(c, http.StatusBadRequest, code.ErrEncodingJSON, err.Error())
		return
	}
	result, err := service.NewTransferSrv().DomesticTransferList(c, req)
	if err != nil {
		code.Fail(c, http.StatusBadRequest, err.(internalerrors.ServiceError).Code, err.(internalerrors.ServiceError).Msg)
		return
	} else {
		code.Success(c, result)
	}
}

// 国内汇款记录详情
func DomesticTransferDetail(c *gin.Context) {
	merOrderNo := c.Query("merOrderNo")
	result, err := service.NewTransferSrv().DomesticTransferDetail(c, merOrderNo)
	if err != nil {
		code.Fail(c, http.StatusBadRequest, err.(internalerrors.ServiceError).Code, err.(internalerrors.ServiceError).Msg)
		return
	} else {
		code.Success(c, result)
	}
}

// 收款关联还原材料
func TradeReceiptOrderDetail(c *gin.Context) {
	flowNo := c.Query("flowNo")
	result, err := service.NewTransferSrv().TradeReceiptOrderDetail(c, flowNo)
	if err != nil {
		code.Fail(c, http.StatusBadRequest, err.(internalerrors.ServiceError).Code, err.(internalerrors.ServiceError).Msg)
		return
	} else {
		code.Success(c, result)
	}
}

func ExportDomesticTransfer(c *gin.Context) {
	var (
		err      error
		filePath string
		// 获取最大导出数
		maxNum  = global.ViperObj.GetInt("export.maxNum")
		account = c.GetString("Account")
		line    = 1
	)
	req := &api.DTListReq{}
	if err = c.ShouldBindJSON(&req); err != nil {
		code.Fail(c, http.StatusBadRequest, code.ErrEncodingJSON, err.Error())
		return
	}
	req.PageSize = maxNum
	result, err := service.NewTransferSrv().DomesticTransferList(c, req)
	if err != nil {
		code.Fail(c, http.StatusBadRequest, err.(internalerrors.ServiceError).Code, err.(internalerrors.ServiceError).Msg)
		return
	}

	f := excelize.NewFile() // 设置单元格的值
	index, _ := f.NewSheet("Sheet1")
	// 这里设置表头
	f.SetCellValue("Sheet1", "A1", "编号")
	f.SetCellValue("Sheet1", "B1", "付款企业名称")
	f.SetCellValue("Sheet1", "C1", "扣款金额")
	f.SetCellValue("Sheet1", "D1", "到账金额")
	f.SetCellValue("Sheet1", "E1", "手续费")
	f.SetCellValue("Sheet1", "F1", "汇率")
	f.SetCellValue("Sheet1", "G1", "收款银行账户")
	f.SetCellValue("Sheet1", "H1", "收款银行名称")
	f.SetCellValue("Sheet1", "I1", "收款方")
	f.SetCellValue("Sheet1", "J1", "结汇类型")
	f.SetCellValue("Sheet1", "K1", "交易类型")
	f.SetCellValue("Sheet1", "L1", "时间")
	f.SetCellValue("Sheet1", "M1", "状态")

	if len(result.List) > maxNum {
		code.Fail(c, http.StatusBadRequest, code.ErrCanNotOpenFile, "导出数据太多，请分批导出")
		return
	}
	// 循环写入数据
	for _, v := range result.List {
		line++
		f.SetCellValue("Sheet1", fmt.Sprintf("A%d", line), v.BizFlowNo)
		if len(v.MerNameCn) > 0 {
			f.SetCellValue("Sheet1", fmt.Sprintf("B%d", line), v.MerNameCn)
		} else if len(v.MerNameEn) > 0 {
			f.SetCellValue("Sheet1", fmt.Sprintf("B%d", line), v.MerNameEn)
		}
		f.SetCellValue("Sheet1", fmt.Sprintf("C%d", line), v.DebitAmount+"人民币")
		f.SetCellValue("Sheet1", fmt.Sprintf("D%d", line), v.Amount+"人民币")
		f.SetCellValue("Sheet1", fmt.Sprintf("E%d", line), v.FeeAmt+v.FeeCurrency)
		f.SetCellValue("Sheet1", fmt.Sprintf("F%d", line), v.Rate)
		f.SetCellValue("Sheet1", fmt.Sprintf("G%d", line), v.BankAcctNo)
		f.SetCellValue("Sheet1", fmt.Sprintf("H%d", line), v.BranchName)
		f.SetCellValue("Sheet1", fmt.Sprintf("I%d", line), v.PayeeName)
		if v.SettlementType == "00" {
			f.SetCellValue("Sheet1", fmt.Sprintf("J%d", line), "普通结汇")
		} else if v.SettlementType == "10" {
			f.SetCellValue("Sheet1", fmt.Sprintf("J%d", line), "极速结汇")
		}

		f.SetCellValue("Sheet1", fmt.Sprintf("K%d", line), v.TradeCodeType)
		f.SetCellValue("Sheet1", fmt.Sprintf("L%d", line), v.UpdatedAt)
		if v.Status == "1" {
			f.SetCellValue("Sheet1", fmt.Sprintf("M%d", line), "成功")
		} else if v.Status == "2" {
			f.SetCellValue("Sheet1", fmt.Sprintf("M%d", line), "失败")
		} else if v.Status == "3" {
			f.SetCellValue("Sheet1", fmt.Sprintf("M%d", line), "处理中")
		}

	}

	f.SetActiveSheet(index)

	var buffer bytes.Buffer
	_ = f.Write(&buffer)
	content := bytes.NewReader(buffer.Bytes())

	fileName := fmt.Sprintf("download/%s%s%s.xlsx", account, `-`, "人民币结汇")
	if filePath, err = upload.UploadToS3Srv(fileName, content); err != nil || len(filePath) == 0 {
		code.Fail(c, http.StatusBadRequest, code.ErrCanNotOpenFile, err.Error())
		return
	}
	code.Success(c, filePath)
}

func ExportInternationTransfer(c *gin.Context) {
	var (
		err      error
		filePath string
		// 获取最大导出数
		maxNum  = global.ViperObj.GetInt("export.maxNum")
		account = c.GetString("Account")
		line    = 1
	)
	req := &api.ITListReq{}
	if err = c.ShouldBindJSON(&req); err != nil {
		code.Fail(c, http.StatusBadRequest, code.ErrEncodingJSON, err.Error())
		return
	}
	req.PageSize = maxNum
	result, err := service.NewTransferSrv().InternationTransferList(c, req)
	if err != nil {
		code.Fail(c, http.StatusBadRequest, err.(internalerrors.ServiceError).Code, err.(internalerrors.ServiceError).Msg)
		return
	}

	f := excelize.NewFile() // 设置单元格的值
	index, _ := f.NewSheet("Sheet1")
	// 这里设置表头
	f.SetCellValue("Sheet1", "A1", "编号")
	f.SetCellValue("Sheet1", "B1", "付款企业名称")
	f.SetCellValue("Sheet1", "C1", "付款金额")
	f.SetCellValue("Sheet1", "D1", "到账金额")
	f.SetCellValue("Sheet1", "E1", "手续费")
	f.SetCellValue("Sheet1", "F1", "汇率")
	f.SetCellValue("Sheet1", "G1", "收款银行账户")
	f.SetCellValue("Sheet1", "H1", "收款方")
	f.SetCellValue("Sheet1", "I1", "收款银行名称")
	f.SetCellValue("Sheet1", "J1", "汇款方式")
	f.SetCellValue("Sheet1", "K1", "汇款目的")
	f.SetCellValue("Sheet1", "L1", "提交时间")
	f.SetCellValue("Sheet1", "M1", "更新时间")
	f.SetCellValue("Sheet1", "N1", "交易附言")
	f.SetCellValue("Sheet1", "O1", "状态")

	if len(result.List) > maxNum {
		code.Fail(c, http.StatusBadRequest, code.ErrCanNotOpenFile, "导出数据太多，请分批导出")
		return
	}
	// 循环写入数据
	for _, v := range result.List {
		line++
		f.SetCellValue("Sheet1", fmt.Sprintf("A%d", line), v.BizFlow)
		if len(v.MerNameCn) > 0 {
			f.SetCellValue("Sheet1", fmt.Sprintf("B%d", line), v.MerNameCn)
		} else if len(v.MerNameEn) > 0 {
			f.SetCellValue("Sheet1", fmt.Sprintf("B%d", line), v.MerNameEn)
		}
		f.SetCellValue("Sheet1", fmt.Sprintf("C%d", line), v.DebitAmount+v.DebitCurrency)
		f.SetCellValue("Sheet1", fmt.Sprintf("D%d", line), v.ArriveAmount+v.ArriveCurrency)
		f.SetCellValue("Sheet1", fmt.Sprintf("E%d", line), v.FeeAmt+v.FeeCurrency)
		f.SetCellValue("Sheet1", fmt.Sprintf("F%d", line), v.Rate)
		f.SetCellValue("Sheet1", fmt.Sprintf("G%d", line), v.PayeeBankAccountNo)
		f.SetCellValue("Sheet1", fmt.Sprintf("H%d", line), v.PayeeFirstName+v.PayeeLastName)
		f.SetCellValue("Sheet1", fmt.Sprintf("I%d", line), v.PayeeBankName)
		f.SetCellValue("Sheet1", fmt.Sprintf("J%d", line), v.PayType)
		f.SetCellValue("Sheet1", fmt.Sprintf("K%d", line), v.PurposeDesc)
		f.SetCellValue("Sheet1", fmt.Sprintf("L%d", line), v.CreatedAt)
		f.SetCellValue("Sheet1", fmt.Sprintf("M%d", line), v.UpdatedAt)
		f.SetCellValue("Sheet1", fmt.Sprintf("N%d", line), v.TradeComments)
		if v.Status == "SUCC" {
			f.SetCellValue("Sheet1", fmt.Sprintf("o%d", line), "成功")
		} else if v.Status == "FAIL" {
			f.SetCellValue("Sheet1", fmt.Sprintf("o%d", line), "失败")
		} else if v.Status == "PROCESS" {
			f.SetCellValue("Sheet1", fmt.Sprintf("o%d", line), "处理中")
		}

	}

	f.SetActiveSheet(index)

	var buffer bytes.Buffer
	_ = f.Write(&buffer)
	content := bytes.NewReader(buffer.Bytes())

	fileName := fmt.Sprintf("download/%s%s%s.xlsx", account, `-`, "国际付款列表导出")
	if filePath, err = upload.UploadToS3Srv(fileName, content); err != nil || len(filePath) == 0 {
		code.Fail(c, http.StatusBadRequest, code.ErrCanNotOpenFile, err.Error())
		return
	}
	code.Success(c, filePath)
}

func ExportTradeReceipt(c *gin.Context) {
	var (
		err      error
		filePath string
		// 获取最大导出数
		maxNum  = global.ViperObj.GetInt("export.maxNum")
		account = c.GetString("Account")
		line    = 1
	)
	req := &api.TradeReceiptListReq{}
	if err = c.ShouldBindJSON(&req); err != nil {
		code.Fail(c, http.StatusBadRequest, code.ErrEncodingJSON, err.Error())
		return
	}
	req.PageSize = maxNum
	result, err := service.NewTransferSrv().TradeReceiptList(c, req)
	if err != nil {
		code.Fail(c, http.StatusBadRequest, err.(internalerrors.ServiceError).Code, err.(internalerrors.ServiceError).Msg)
		return
	}

	f := excelize.NewFile() // 设置单元格的值
	index, _ := f.NewSheet("Sheet1")
	// 这里设置表头
	f.SetCellValue("Sheet1", "A1", "流水号")
	f.SetCellValue("Sheet1", "B1", "收款企业名称(中文)")
	f.SetCellValue("Sheet1", "C1", "收款企业名称(英文)")
	f.SetCellValue("Sheet1", "D1", "收款金额")
	f.SetCellValue("Sheet1", "E1", "到账金额")
	f.SetCellValue("Sheet1", "F1", "手续费")
	f.SetCellValue("Sheet1", "G1", "收款银行账户")
	f.SetCellValue("Sheet1", "H1", "付款名称")
	f.SetCellValue("Sheet1", "I1", "时间")
	f.SetCellValue("Sheet1", "J1", "状态")

	if len(result.List) > maxNum {
		code.Fail(c, http.StatusBadRequest, code.ErrCanNotOpenFile, "导出数据太多，请分批导出")
		return
	}
	// 循环写入数据
	for _, v := range result.List {
		line++
		f.SetCellValue("Sheet1", fmt.Sprintf("A%d", line), v.FlowNo)
		f.SetCellValue("Sheet1", fmt.Sprintf("B%d", line), v.MerNameCn)
		f.SetCellValue("Sheet1", fmt.Sprintf("C%d", line), v.MerNameEn)
		f.SetCellValue("Sheet1", fmt.Sprintf("D%d", line), v.ReceiveAmount+v.ReceiveCurrency)
		f.SetCellValue("Sheet1", fmt.Sprintf("E%d", line), v.ActualReceiveAmount+v.ReceiveCurrency)
		f.SetCellValue("Sheet1", fmt.Sprintf("F%d", line), v.FeeAmount+v.FeeCurrency)
		f.SetCellValue("Sheet1", fmt.Sprintf("G%d", line), v.AccountNo)
		f.SetCellValue("Sheet1", fmt.Sprintf("H%d", line), v.SenderName)
		f.SetCellValue("Sheet1", fmt.Sprintf("I%d", line), v.CreatedAt)
		if v.TradeStatus == "" {
			f.SetCellValue("Sheet1", fmt.Sprintf("J%d", line), "带入帐")
		} else if v.TradeStatus == "01" {
			f.SetCellValue("Sheet1", fmt.Sprintf("J%d", line), "失败")
		} else if v.TradeStatus == "02" {
			f.SetCellValue("Sheet1", fmt.Sprintf("J%d", line), "成功")
		}
	}

	f.SetActiveSheet(index)

	var buffer bytes.Buffer
	_ = f.Write(&buffer)
	content := bytes.NewReader(buffer.Bytes())

	fileName := fmt.Sprintf("download/%s%s%s.xlsx", account, `-`, "收款列表导出")
	if filePath, err = upload.UploadToS3Srv(fileName, content); err != nil || len(filePath) == 0 {
		code.Fail(c, http.StatusBadRequest, code.ErrCanNotOpenFile, err.Error())
		return
	}
	code.Success(c, filePath)
}
